<template>
  <div class="login-page">
    <div class="container">
      <div class="hero-section">
        <h1 class="hero-title">欢迎来到我们的平台</h1>
        <p class="hero-subtitle">加入我们，体验全新的产品服务。无论您是个人用户还是企业客户，我们都为您准备了最适合的解决方案。</p>

        <div class="features">
          <div class="feature" v-for="feature in features" :key="feature.id">
            <span class="feature-icon">{{ feature.icon }}</span>
            <span>{{ feature.text }}</span>
          </div>
        </div>
      </div>

      <div class="auth-container">
        <div class="auth-card">
          <div class="auth-header">
            <h2 class="auth-title">欢迎回来</h2>
            <p class="auth-subtitle">请登录您的账户以继续使用我们的服务</p>
          </div>

          <div class="tabs">
            <div
              class="tab"
              :class="{ active: activeTab === 'login' }"
              @click="setActiveTab('login')"
            >
              登录
            </div>
            <div
              class="tab"
              :class="{ active: activeTab === 'register' }"
              @click="setActiveTab('register')"
            >
              注册
            </div>
          </div>

          <!-- 登录表单 -->
          <form
            class="form-container"
            :class="{ active: activeTab === 'login' }"
            @submit.prevent="handleLogin"
            v-show="activeTab === 'login'"
          >
            <div class="form-group">
              <label class="form-label" for="login-email">邮箱地址</label>
              <input
                type="email"
                id="login-email"
                class="form-input"
                placeholder="请输入您的邮箱"
                v-model="loginForm.email"
                required
              >
            </div>

            <div class="form-group">
              <label class="form-label" for="login-password">密码</label>
              <input
                type="password"
                id="login-password"
                class="form-input"
                placeholder="请输入您的密码"
                v-model="loginForm.password"
                required
              >
            </div>

            <div class="form-options">
              <div class="checkbox-container">
                <input
                  type="checkbox"
                  id="remember-me"
                  v-model="loginForm.remember"
                >
                <label for="remember-me">记住我</label>
              </div>
              <a href="#" class="forgot-link">忘记密码?</a>
            </div>

            <button type="submit" class="btn btn-primary" :disabled="loginLoading">
              {{ loginLoading ? '登录中...' : '登录' }}
            </button>
          </form>

          <!-- 注册表单 -->
          <form
            class="form-container"
            :class="{ active: activeTab === 'register' }"
            @submit.prevent="handleRegister"
            v-show="activeTab === 'register'"
          >
            <div class="form-group">
              <label class="form-label" for="register-name">姓名</label>
              <input
                type="text"
                id="register-name"
                class="form-input"
                placeholder="请输入您的姓名"
                v-model="registerForm.name"
                required
              >
            </div>

            <div class="form-group">
              <label class="form-label" for="register-email">邮箱地址</label>
              <input
                type="email"
                id="register-email"
                class="form-input"
                placeholder="请输入您的邮箱"
                v-model="registerForm.email"
                required
              >
            </div>

            <!-- 验证码输入框 -->
            <div class="form-group">
              <label class="form-label" for="verification-code">验证码</label>
              <div class="verification-container">
                <input
                  type="text"
                  id="verification-code"
                  class="form-input verification-input"
                  placeholder="请输入验证码"
                  v-model="registerForm.verificationCode"
                  required
                >
                <button
                  type="button"
                  class="btn-verification"
                  @click="sendVerificationCodeHandler"
                  :disabled="verificationLoading || countdown > 0"
                >
                  {{ verificationButtonText }}
                </button>
              </div>
            </div>

            <div class="form-group">
              <label class="form-label" for="register-password">密码</label>
              <input
                type="password"
                id="register-password"
                class="form-input"
                placeholder="请设置密码"
                v-model="registerForm.password"
                required
              >
            </div>

            <div class="form-group">
              <label class="form-label" for="register-confirm">确认密码</label>
              <input
                type="password"
                id="register-confirm"
                class="form-input"
                placeholder="请再次输入密码"
                v-model="registerForm.confirmPassword"
                required
              >
            </div>

            <div class="form-options">
              <div class="checkbox-container">
                <input
                  type="checkbox"
                  id="agree-terms"
                  v-model="registerForm.agreeTerms"
                  required
                >
                <label for="agree-terms">我同意<a href="#">服务条款</a>和<a href="#">隐私政策</a></label>
              </div>
            </div>

            <button type="submit" class="btn btn-primary" :disabled="registerLoading">
              {{ registerLoading ? '注册中...' : '注册' }}
            </button>
          </form>

          <div class="divider">
            <span>或使用以下方式登录</span>
          </div>

          <div class="social-login">
            <button
              class="btn-social"
              v-for="provider in socialProviders"
              :key="provider.name"
              @click="handleSocialLogin(provider.name)"
            >
              <span class="social-icon">{{ provider.icon }}</span>
              <span>{{ provider.name }}</span>
            </button>
          </div>

          <div class="footer">
            <p>登录即表示您同意我们的<a href="#">服务条款</a>和<a href="#">隐私政策</a></p>
          </div>
        </div>
      </div>
    </div>

    <!-- 消息提示 -->
    <div v-if="message.show" :class="['message', message.type]">
      {{ message.text }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { loginAndSaveToken, type LoginParams } from '@/api/login'
import {
  registerUser,
  sendVerificationCode,
  type RegisterParams
} from '@/api/auth'
import { saveAuthToken } from '@/utils/auth'


const router = useRouter()

// 类型定义
interface Feature {
  id: number
  icon: string
  text: string
}

interface SocialProvider {
  name: string
  icon: string
}

interface LoginFormData {
  email: string
  password: string
  remember: boolean
}

interface RegisterFormData {
  name: string
  email: string
  password: string
  confirmPassword: string
  verificationCode: string
  agreeTerms: boolean
}

interface MessageState {
  show: boolean
  text: string
  type: 'success' | 'error' | 'warning' | 'info'
}

type TabType = 'login' | 'register'

// 响应式数据
const activeTab = ref<TabType>('login')
const loginLoading = ref(false)
const registerLoading = ref(false)
const verificationLoading = ref(false)
const countdown = ref(0)
let countdownTimer: number | null = null

const message = reactive<MessageState>({
  show: false,
  text: '',
  type: 'info'
})

const features = ref<Feature[]>([
  { id: 1, icon: '🚀', text: '快速部署，即刻使用' },
  { id: 2, icon: '🏆', text: '行业领先的安全保障' },
  { id: 3, icon: '⏰', text: '7x24小时全天候服务' },
  { id: 4, icon: '🛡', text: '数据加密，隐私保护' }
])

const socialProviders = ref<SocialProvider[]>([
  { name: 'Google', icon: '🔍' },
  { name: 'GitHub', icon: '🐱' },
  { name: 'LinkedIn', icon: '💼' }
])

const loginForm = reactive<LoginFormData>({
  email: '',
  password: '',
  remember: false
})

const registerForm = reactive<RegisterFormData>({
  name: '',
  email: '',
  password: '',
  confirmPassword: '',
  verificationCode: '',
  agreeTerms: false
})

// 计算属性
const verificationButtonText = computed(() => {
  if (verificationLoading.value) return '发送中...'
  if (countdown.value > 0) return `${countdown.value}s后重发`
  return '发送验证码'
})

// 工具函数
const showMessage = (text: string, type: MessageState['type'] = 'info') => {
  message.text = text
  message.type = type
  message.show = true

  setTimeout(() => {
    message.show = false
  }, 3000)
}

const startCountdown = () => {
  countdown.value = 60
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer!)
      countdownTimer = null
    }
  }, 1000)
}

// 发送验证码
const sendVerificationCodeHandler = async () => {
  if (!registerForm.email) {
    showMessage('请先输入邮箱地址', 'warning')
    return
  }

  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email)) {
    showMessage('请输入有效的邮箱地址', 'warning')
    return
  }

  verificationLoading.value = true

  try {
    const result = await sendVerificationCode(registerForm.email)

    if (result.success) {
      showMessage('验证码已发送，请查收邮件', 'success')
      startCountdown()
    } else {
      showMessage(result.message || '验证码发送失败', 'error')
    }
  } catch (error) {
    console.error('Send verification code failed:', error)
    showMessage('验证码发送失败，请检查网络连接', 'error')
  } finally {
    verificationLoading.value = false
  }
}

// 方法
const setActiveTab = (tab: TabType) => {
  activeTab.value = tab
}

const handleLogin = async () => {
  // 表单验证
  if (!loginForm.email) {
    showMessage('请输入邮箱地址', 'warning')
    return
  }

  if (!loginForm.password) {
    showMessage('请输入密码', 'warning')
    return
  }

  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(loginForm.email)) {
    showMessage('请输入有效的邮箱地址', 'warning')
    return
  }

  loginLoading.value = true

  try {
    const params: LoginParams = {
      username: loginForm.email, // 使用邮箱作为用户名
      password: loginForm.password,
    }

    // 使用封装好的登录函数
    const result = await loginAndSaveToken(params)

    if (result.success && result.code === 200 && result.data) {
      showMessage('登录成功！', 'success')

      // 清空表单
      Object.assign(loginForm, {
        email: '',
        password: '',
        remember: false
      })

      // 获取重定向路径，如果没有则跳转到默认页面
      const redirect = router.currentRoute.value.query.redirect as string

      setTimeout(() => {
        router.push(redirect || '/TheaterList')
      }, 1000) // 延迟跳转，让用户看到成功消息

    } else {
      showMessage(result.message || '登录失败，请检查用户名和密码', 'error')
    }
  } catch (error) {
    console.error('Login failed:', error)
    showMessage('登录失败，请检查网络连接', 'error')
  } finally {
    loginLoading.value = false
  }
}
const handleRegister = async () => {
  // 表单验证
  if (registerForm.password !== registerForm.confirmPassword) {
    showMessage('两次输入的密码不一致', 'warning')
    return
  }

  if (registerForm.password.length < 6) {
    showMessage('密码长度至少为6位', 'warning')
    return
  }

  if (!registerForm.verificationCode) {
    showMessage('请输入验证码', 'warning')
    return
  }

  if (!registerForm.agreeTerms) {
    showMessage('请同意服务条款和隐私政策', 'warning')
    return
  }

  registerLoading.value = true

  try {
    const params: RegisterParams = {
      email: registerForm.email,
      verification_code: registerForm.verificationCode,
      name: registerForm.name,
      password: registerForm.password,
    }

    const result = await registerUser(params)

    if (result.success && result.code === 200 && result.data) {
      showMessage('注册成功！', 'success')

      // 使用统一的 saveAuthToken 函数
      saveAuthToken(result.data)

      // 清空表单
      Object.assign(registerForm, {
        name: '',
        email: '',
        password: '',
        confirmPassword: '',
        verificationCode: '',
        agreeTerms: false
      })

      setTimeout(() => {
        router.push('/TheaterList')
      }, 1000)

    } else {
      showMessage(result.message || '注册失败', 'error')
    }
  } catch (error) {
    console.error('Registration failed:', error)
    showMessage('注册失败，请检查网络连接', 'error')
  } finally {
    registerLoading.value = false
  }
}


const handleSocialLogin = (provider: string) => {
  console.log('Social login:', provider)
  showMessage(`${provider} 登录功能待实现`, 'info')
}

// 清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>

<style scoped>
.login-page {
  --primary-blue: #3b82f6;
  --dark-blue: #2563eb;
  --cyan-blue: #06b6d4;
  --dark-cyan: #0891b2;
  --bg-light: #f8fafc;
  --text-primary: #1f2937;
  --text-secondary: #6b7280;
  --text-muted: #64748b;
  --text-disabled: #94a3b8;
  --success: #10b981;
  --warning: #f59e0b;
  --error: #ef4444;
  --info: #06b6d4;

  --font-xl: 2.5rem;
  --font-lg: 1.75rem;
  --font-md: 1.25rem;
  --font-base: 1rem;
  --font-sm: 0.875rem;
  --font-xs: 0.75rem;

  --space-xl: 4rem;
  --space-lg: 2.5rem;
  --space-md: 1.5rem;
  --space-sm: 1rem;
  --space-xs: 0.5rem;

  --radius-lg: 1rem;
  --radius-md: 0.75rem;
  --radius-sm: 0.5rem;

  --shadow-card: 0 4px 20px rgba(59, 130, 246, 0.08);
  --shadow-hover: 0 8px 30px rgba(59, 130, 246, 0.15);
  --shadow-deep: 0 20px 25px -5px rgba(0, 0, 0, 0.1);

  --transition: 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;

  background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(6, 182, 212, 0.05) 100%),
              radial-gradient(circle at 10% 20%, rgba(59, 130, 246, 0.03) 0%, transparent 20%),
              radial-gradient(circle at 90% 80%, rgba(6, 182, 212, 0.03) 0%, transparent 20%),
              #f8fafc;
  background-size: 100% 100%, 80px 80px, 80px 80px, auto;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--space-md) var(--space-lg);
  color: var(--text-primary);
  line-height: 1.6;
}

.container {
  max-width: 1400px;
  width: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--space-xl);
  align-items: center;
  padding: 0 var(--space-lg);
}

.hero-section {
  padding: var(--space-lg) var(--space-md);
  min-height: 500px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.hero-title {
  font-size: var(--font-xl);
  font-weight: 700;
  line-height: 1.2;
  margin-bottom: var(--space-md);
  background: linear-gradient(135deg, var(--primary-blue), var(--cyan-blue));
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.hero-subtitle {
  font-size: var(--font-md);
  color: var(--text-secondary);
  margin-bottom: var(--space-lg);
  max-width: 600px;
  line-height: 1.6;
}

.features {
  display: flex;
  flex-direction: column;
  gap: var(--space-md);
  margin-top: var(--space-lg);
}

.feature {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  color: var(--text-muted);
  padding: var(--space-xs) 0;
}

.feature-icon {
  font-size: 1.25rem;
  width: 1.5rem;
  display: inline-block;
}

.auth-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--space-md);
}

.auth-card {
  background: rgba(255, 255, 255, 0.7);
  border: 1px solid rgba(59, 130, 246, 0.1);
  border-radius: var(--radius-lg);
  padding: var(--space-lg);
  width: 100%;
  max-width: 480px;
  box-shadow: var(--shadow-card);
  backdrop-filter: blur(10px);
  transition: transform var(--transition), box-shadow var(--transition);
}

.auth-card:hover {
  transform: translateY(-3px);
  box-shadow: var(--shadow-hover);
}

.auth-header {
  text-align: center;
  margin-bottom: var(--space-lg);
}

.auth-title {
  font-size: var(--font-lg);
  font-weight: 600;
  margin-bottom: var(--space-xs);
  color: var(--text-primary);
}

.auth-subtitle {
  color: var(--text-secondary);
  font-size: var(--font-sm);
  line-height: 1.5;
}

.tabs {
  display: flex;
  margin-bottom: var(--space-md);
  border-bottom: 1px solid rgba(59, 130, 246, 0.1);
}

.tab {
  flex: 1;
  text-align: center;
  padding: var(--space-sm) 0;
  font-weight: 500;
  color: var(--text-muted);
  cursor: pointer;
  transition: color var(--transition);
  position: relative;
}

.tab.active {
  color: var(--primary-blue);
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background: var(--primary-blue);
  border-radius: 2px;
}

.form-container {
  display: block;
}

.form-group {
  margin-bottom: var(--space-md);
}

.form-label {
  display: block;
  margin-bottom: var(--space-xs);
  font-size: var(--font-sm);
  font-weight: 500;
  color: var(--text-primary);
}

.form-input {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 1px solid rgba(59, 130, 246, 0.2);
  border-radius: var(--radius-sm);
  font-size: var(--font-base);
  transition: border-color var(--transition), box-shadow var(--transition);
  background: rgba(255, 255, 255, 0.8);
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: var(--primary-blue);
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.verification-container {
  display: flex;
  gap: var(--space-xs);
}

.verification-input {
  flex: 1;
}

.btn-verification {
  padding: 0.75rem 1rem;
  border: 1px solid var(--primary-blue);
  border-radius: var(--radius-sm);
  background: transparent;
  color: var(--primary-blue);
  font-size: var(--font-sm);
  font-weight: 500;
  cursor: pointer;
  transition: all var(--transition);
  white-space: nowrap;
  min-width: 100px;
}

.btn-verification:hover:not(:disabled) {
  background: var(--primary-blue);
  color: white;
}

.btn-verification:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--space-md);
  font-size: var(--font-sm);
}

.checkbox-container {
  display: flex;
  align-items: center;
  gap: var(--space-xs);
  color: var(--text-muted);
}

.checkbox-container a {
  color: var(--primary-blue);
  text-decoration: none;
  font-weight: 500;
}

.forgot-link {
  color: var(--primary-blue);
  text-decoration: none;
  font-weight: 500;
  transition: color var(--transition);
}

.forgot-link:hover {
  color: var(--dark-blue);
}

.btn {
  display: block;
  width: 100%;
  padding: 0.875rem 2rem;
  border: none;
  border-radius: var(--radius-md);
  font-size: var(--font-base);
  font-weight: 600;
  cursor: pointer;
  transition: all var(--transition);
  text-align: center;
  min-width: 160px;
}

.btn-primary {
  background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
  color: white;
  box-shadow: 0 4px 6px rgba(59, 130, 246, 0.2);
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: var(--shadow-hover);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none !important;
}

.divider {
  display: flex;
  align-items: center;
  margin: var(--space-lg) 0;
  color: var(--text-muted);
  font-size: var(--font-sm);
}

.divider::before, .divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background: rgba(59, 130, 246, 0.1);
}

.divider span {
  padding: 0 var(--space-sm);
}

.social-login {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: var(--space-sm);
}

.btn-social {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--space-xs);
  padding: 0.75rem;
  border: 1px solid rgba(59, 130, 246, 0.2);
  border-radius: var(--radius-sm);
  background: rgba(255, 255, 255, 0.8);
  font-size: var(--font-sm);
  font-weight: 500;
  color: var(--text-primary);
  cursor: pointer;
  transition: all var(--transition);
}

.btn-social:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(59, 130, 246, 0.1);
  border-color: rgba(59, 130, 246, 0.3);
}

.social-icon {
  font-size: 1.125rem;
}

.footer {
  text-align: center;
  margin-top: var(--space-lg);
  color: var(--text-muted);
  font-size: var(--font-sm);
  line-height: 1.5;
}

.footer a {
  color: var(--primary-blue);
  text-decoration: none;
  font-weight: 500;
}

.message {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 1rem 1.5rem;
  border-radius: var(--radius-md);
  color: white;
  font-weight: 500;
  z-index: 1000;
  animation: slideIn 0.3s ease-out;
  max-width: 300px;
  word-wrap: break-word;
}

.message.success {
  background: var(--success);
}

.message.error {
  background: var(--error);
}

.message.warning {
  background: var(--warning);
}

.message.info {
  background: var(--info);
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .container {
    max-width: 1000px;
    padding: 0 var(--space-md);
    gap: var(--space-lg);
  }
}

@media (max-width: 1024px) {
  .login-page {
    padding: var(--space-md);
  }

  .container {
    grid-template-columns: 1fr;
    gap: var(--space-lg);
    padding: 0;
  }

  .hero-section {
    text-align: center;
    padding: var(--space-lg) var(--space-md);
    min-height: auto;
  }

  .hero-title {
    font-size: 2rem;
  }

  .hero-subtitle {
    max-width: 100%;
  }
}

@media (max-width: 768px) {
  .login-page {
    --font-xl: 2rem;
    --font-lg: 1.5rem;
    padding: var(--space-sm);
  }

  .container {
    gap: var(--space-md);
  }

  .hero-section {
    padding: var(--space-md);
  }

  .auth-card {
    padding: var(--space-md);
    max-width: 100%;
  }

  .auth-container {
    padding: var(--space-sm);
  }

  .social-login {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 576px) {
  .login-page {
    padding: var(--space-xs);
  }

  .hero-title {
    font-size: 1.75rem;
  }

  .hero-section {
    padding: var(--space-sm);
  }

  .auth-card {
    padding: var(--space-md) var(--space-sm);
  }

  .form-options {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--space-sm);
  }

  .features {
    gap: var(--space-sm);
  }

  .verification-container {
    flex-direction: column;
  }

  .verification-input {
    margin-bottom: var(--space-xs);
  }

  .btn-verification {
    min-width: auto;
  }

  .message {
    right: 10px;
    left: 10px;
    max-width: none;
  }
}
</style>
